package com.celebracion;

import java.io.File;
import java.io.IOException;




import com.celebracion.model.EventoModel;
import com.celebracion.user.CrearEventoActivity;
import com.celebracion.user.MenuDialogActivity;
import com.celebracion.user.PasswordUserActivity;
import com.celebracion.user.VisorEventosPrevistosActivity;
import com.celebracion.util.CameraUtil;
import com.celebracion.util.DBUtil;
import com.celebracion.util.FileUtil;
import com.celebracion.util.MonitorHandler;
import com.celebracion.util.SystemUiHider;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.FrameLayout;



 /**
  * @todo Esta clase esta lista a falta de activar el killStatusBar
  * @author Gabi
  *
  */
public class NombresActivity extends Activity implements OnCompletionListener //Para ir cargando los videos
{
	
	
	VideoView videoView;
	MediaPlayer mediaPlayer;
	EventoModel eventoActivo;
	File[] archivos;
	int posVideos=0;
	Thread hiloMonitor=null;
	String pathVideoFileOutput;
	Camera mCamera;
	CameraPreview mPreview;
	FrameLayout videoView1;
	TextView contadorTextView;
	RelativeLayout rLayout;
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//Quitamos barra de titulo de la aplicacion
		 requestWindowFeature(Window.FEATURE_NO_TITLE);
    	
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_nombres);
		//videoView=(VideoView)findViewById(R.id.videoView1);
		//videoView.setOnCompletionListener(this);
		contadorTextView=(TextView)findViewById(R.id.contadorTextView);
		rLayout=(RelativeLayout)findViewById(R.id.RelativeLayout1);
		//killStatusBar();
		MonitorHandler.startMonitor();

	}
	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		videoView1=	((FrameLayout)findViewById(R.id.videoView1));
		
		
				
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// Create an instance of Camera
	    mCamera = CameraUtil.getCameraInstance();
		mPreview = new CameraPreview(this, mCamera);
		videoView1.addView(mPreview);
		contadorTextView.setVisibility(View.GONE);
	

	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mCamera.release();
		videoView1.removeAllViews();
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
	}
	
	private void playVideo(String videoPath) {
		videoView.setVideoPath(videoPath);
		videoView.start();

	}
	public void grabarVideo2(View view){
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);
		intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
		pathVideoFileOutput=FileUtil.getInternalFile(FileUtil.MEDIA_TYPE_VIDEO, DBUtil.getInstance(this.getBaseContext()).getEventoActivo().getId(),FileUtil.DIRECTORIO_APP_TEMP,this.getBaseContext()).toString();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, pathVideoFileOutput);
		intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false);
		 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

		    // start the Video Capture Intent
		    startActivityForResult(intent, 33);
	}
	
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		Uri selectedVideo=intent.getData();
		pathVideoFileOutput=getRealPathFromURI(selectedVideo);
		previsualizar();
	}
	public void previsualizar() {
		try {
			//Se le dan permisos 777 al fichero para que lo pueda ejecutar el videoView ya que usa un componente externo
			Runtime.getRuntime().exec("chmod 777 "+pathVideoFileOutput);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		Intent intent = new Intent(this, VideoPreviewActivity.class);
		intent.putExtra("video", pathVideoFileOutput);
		startActivity(intent);
	}
	
	public void grabarVideo(View view){
		new Thread(new Runnable() {
			public void run() {

				rLayout.post(new Runnable() {
					@Override
					public void run() {
						contadorTextView.setVisibility(View.VISIBLE);
					}
				});

				for (int i = 5; i >= 0; i--) {
					rLayout.post(new CountDownRunnable(i) {
						@Override
						public void run() {
							contadorTextView.setVisibility(View.VISIBLE);
							contadorTextView.setText(this.getCountDown() + "");
						}
					});
					delay(1000);
				}

				rLayout.post(new Runnable() {
					@Override
					public void run() {
						contadorTextView.setVisibility(View.GONE);
					}
				});
				
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);
				intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
				pathVideoFileOutput=FileUtil.getInternalFile(FileUtil.MEDIA_TYPE_VIDEO, DBUtil.getInstance(NombresActivity.this.getBaseContext()).getEventoActivo().getId(),FileUtil.DIRECTORIO_APP_TEMP,NombresActivity.this.getBaseContext()).toString();
				intent.putExtra(MediaStore.EXTRA_OUTPUT, pathVideoFileOutput);
				intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

				// start the Video Capture Intent
				startActivityForResult(intent, 33);

			}

		}).start();
		
		
		
		
		
		//startActivity(new Intent(this,CameraActivity.class));
	}
	
	public void hacerFoto(View view){
		//Foto2Activity es la que hace las chapucillas
		startActivity(new Intent(this,FotoActivity.class));
	}
	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	  
	    getMenuInflater().inflate(R.menu.initial_menu, menu);
	    return true;
	    
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        
	        case R.id.itCrearEvento:
	        	startActivity(new Intent(this,CrearEventoActivity.class));
	        	return true;
	        case R.id.itVerEventosPrevistos:
	        	startActivity(new Intent(this,VisorEventosPrevistosActivity.class));
	        	return true;	
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}*/
	Thread hilo=null;
	int pulsaciones=0;
	
	public void mostrarMenu(View view){
		if(hilo==null){
		hilo=new Thread(new Runnable(){

			@Override
			public void run() {
				 try{
				    	Thread.sleep(3000);
				    } catch(InterruptedException e) {}
				 pulsaciones=0;
				 hilo=null;
				
			}});
		hilo.start();
		}else{
			pulsaciones++;
			if(pulsaciones==5)
				startActivity(new Intent(this,PasswordUserActivity.class));
		}
	}
	
	
	private void killStatusBar()
	 {
	     Process proc = null;

	     String ProcID = "79"; //HONEYCOMB AND OLDER

	     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
	         ProcID = "42"; //ICS AND NEWER
	     }

	     try {
	         proc = Runtime.getRuntime().exec(new String[] 
	        		 { "su", "-c", "service call activity "+ProcID+" s16 com.android.systemui" });
	     } catch (IOException e) {
	         Log.w("","Failed to kill task bar (1).");
	         e.printStackTrace();
	     }
	     try {
	         proc.waitFor();
	     } catch (InterruptedException e) {
	         Log.w("","Failed to kill task bar (2).");
	         e.printStackTrace();
	     }

	 }


	@Override
	public void onCompletion(MediaPlayer mp) {
		posVideos=(posVideos+1)%archivos.length;
		//mediaPlayer.release();
		playVideo(archivos[posVideos].getAbsolutePath());
		
		
	}
	
	void delay(int milliseconds) {
		try {
			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {
		}
	}
	
	private abstract class CountDownRunnable implements Runnable {
		private int countDown;

		public CountDownRunnable(int a) {
			countDown = a;
		}

		public int getCountDown() {
			return countDown;
		}

	}
	
}
